import psycopg2
def transfer_money(from_account_id, to_account_id, amount):
    try:
        connection = psycopg2.connect(
        user="postgres",
        password="ffxshlsy666",
        host="localhost",
        port="5432",
        database="transaction_lab"
        )
        
        cursor = connection.cursor()
        
        # Start the transaction
        connection.autocommit = False
        # 1. Check if the account has enough fund
        check_balance = "SELECT balance FROM accounts WHERE account_id = %s"
        cursor.execute(check_balance, (from_account_id,))
        current_balance = cursor.fetchone()[0]
        
        if current_balance < amount:
        # Cancel the transaction if funds are not enough
            print(f"Insufficient funds ! Actual balance : {current_balance}, Amount requested: {amount}")
            connection.rollback()
            return False
        
        # 2. Debit the source account
        update_source = "UPDATE accounts SET balance = balance - %s WHERE account_id = %s"
        cursor.execute(update_source, (amount, from_account_id))
        
        # 3. Credit the destination account
        update_destination = "UPDATE accounts SET balance = balance + %s WHERE account_id = %s"
        cursor.execute(update_destination, (amount, to_account_id))
        
        # 4. Record the transaction
        record_transaction = """
        INSERT INTO transactions (from_account, to_account, amount)
        VALUES (%s, %s, %s)
        """
        cursor.execute(record_transaction, (from_account_id, to_account_id, amount))
        
        # 5. Validate the transaction
        connection.commit()
        print(f"Transfer of {amount} € successfully completed from ID {from_account_id} to ID {to_account_id}")
        return True
        
    except (Exception, psycopg2.Error) as error:
        if connection:
            connection.rollback()
        print("Error during the transacation:", error)
        return False
    finally:
        if connection:
            cursor.close()
            connection.close()
if __name__ == "__main__":
 # Exemple de transfert de 200€ du compte 1 vers le compte 2
 transfer_money(1, 2, 200.00)